import { reqVerifyCode, reqRegister, reqLogin, reqUserInfo, reqLogout } from '@/api/index'

const state = {
    verifyCode: '',
    token: '',
    userInfo: {}
}
const mutations = {
    GETVERIFYCODE(state, val) {
        state.verifyCode = val
    },
    USERLOGIN(state, val) {
        state.token = val
    },
    GETUSERINFO(state, val) {
        state.userInfo = val;
    },
    USERLOGOUT(state) {
        state.token = ''
        state.userInfo = {}
        localStorage.removeItem('TOKEN')
    }
}
const actions = {
    async getVerifyCode(context, phone) {
        const res = await reqVerifyCode(phone)
        if (res.code == 200) {
            context.commit('GETVERIFYCODE', res.data)
        }
    },
    async userRegister(context, user) {
        const res = await reqRegister(user)
        if (res.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async userLogin(context, user) {
        const res = await reqLogin(user)
        if (res.code == 200) {
            // 通常都是用token找服务端请求用户信息
            localStorage.setItem('TOKEN', res.data.token)
            context.commit('USERLOGIN', res.data.token)
        }
    },
    async getUserInfo(context) {
        const result = await reqUserInfo()
        console.log(result);
        if (result.code == 200) {
            context.commit("GETUSERINFO", result.data);
        }
    },
    async userLogout(context) {
        const res = await reqLogout()
        if (res.code == 200) {
            context.commit('USERLOGOUT')
        }
    }
}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}